import 'dart:async';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

part 'provider.dart';

typedef TapClick = Future<bool> Function();
typedef ValueChange = String Function(int countDown);

class CountDownWidget extends StatelessWidget {
  final TapClick? onTap;
  final ValueChange? onValueChange;
  final TextStyle textStyle;
  final TextStyle disabledTextStyle;
  final String hint;
  final String repeat;
  final CountDownProvider? provider;

  const CountDownWidget(
      {super.key,
      this.onTap,
      this.onValueChange,
      this.textStyle = const TextStyle(fontSize: 16.0, color: Colors.blue),
      this.disabledTextStyle = const TextStyle(fontSize: 16.0, color: Colors.grey),
      this.hint = '获取验证码',
      this.repeat = '重新获取',
      this.provider});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (BuildContext context) => provider ?? CountDownProvider(),
      builder: (context, child) => _buildPage(context),
    );
  }

  Widget _buildPage(BuildContext context) {
    return Consumer<CountDownProvider>(
      builder: (context, provider, child) {
        return InkWell(
          onTap: () async {
            if (!provider.isFinish) {
              return;
            }
            if (onTap != null) {
              bool result = await onTap!.call();
              if (!result) {
                return;
              }
              provider.startCountDown();
            }
          },
          child: Container(
            child: Text(
                provider.isFinish
                    ? !provider.isFirst
                        ? repeat
                        : hint
                    : onValueChange == null
                        ? '${provider.currentTime}s'
                        : onValueChange!.call(provider.currentTime),
                style: provider.isFinish && provider.isFirst ? textStyle : disabledTextStyle),
          ),
        );
      },
    );
  }
}
